package com.meme.editor.gui.level;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JPanel;
import javax.swing.JSplitPane;

import org.apache.log4j.Logger;

import com.meme.editor.gui.FileEditor;
import com.meme.editor.gui.PropertyEditPanel;
import com.meme.io.editor.LevelXmlFileWriter;
import com.meme.util.FileUtil;

import com.meme.editor.level.LevelFile;

import com.meme.io.editor.FileCache;

public class LevelMainPanel extends JPanel implements FileEditor 
{
	static Logger logger = Logger.getLogger (LevelMainPanel.class);

	LevelFile mLevelFile;
	
	LevelTreeView mLevelTreeView;
	LevelMainView mLevelMainView;
	
	public LevelMainPanel (LevelFile levelFile)
	{
		mLevelFile = levelFile;
		
		mLevelMainView = new LevelMainView (levelFile);
		mLevelTreeView = new LevelTreeView (levelFile);
		
		mLevelMainView.setLevelTreeView (mLevelTreeView);
		mLevelTreeView.setLevelMainView (mLevelMainView);
		
		JSplitPane mSplitPane = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, 
				mLevelTreeView, 
				mLevelMainView );

		mSplitPane.setPreferredSize ( new Dimension (680, 500) );
		mSplitPane.setDividerLocation (200);
		mSplitPane.setDividerSize  (5);
		mSplitPane.setResizeWeight (0.0);
		
		setLayout ( new BorderLayout() );
		add (mSplitPane, BorderLayout.CENTER); 
		
	}
	
	@Override
	public String getTitle ()
	{
		return mLevelFile.getName();
	}
	
	@Override
	public boolean isFileModified ()
	{
		return mLevelFile.isModified();
	}
	
	@Override
	public boolean isFileNew ()
	{
		return mLevelFile.getHostFilename() == null;
		       // ! FileUtil.getFile (mLevelFile.getHostFilename()).exists();
	}
	
	@Override
	public boolean onSaveFile (String filename)
	{
		if (filename == null)
		{
			logger.assertLog( ! isFileNew (), "What is the filename?!");
			
			filename = mLevelFile.getHostFilename();
		}
		
		new LevelXmlFileWriter ().writeToFile (mLevelFile, filename);
		mLevelFile.setModified(false);
		
		FileCache.registerLoadedFileAsset (mLevelFile.getHostFilename(), mLevelFile);
		
		return true;
	}
	
	@Override
	public Component getComponent ()
	{
		return this;
	}
}
